/**
 * Created by sjg on 17/2/13.
 */

var express = require('express');
var router = express.Router();
var superagent = require('superagent');// 使用了superagent来发起请求
var ItbFeedbackModel = require('../../../common/mysql/mapping/ItbFeedbackModel');
var ItbUserModel = require('../../../common/mysql/mapping/ItbUserModel');
var usersUtil = require('../util/usersUtil.js');
var CONFIG = require('../../../common/config');
var EncryptUtil = require('../../../common/util/EncryptUtil');
var CODE = require('../../../common/code');

var checkUtil = require('../util/checkUtil');
var printUtil = require('../util/printUtil');
var usersUtil = require('../util/usersUtil');
var payUtil = require('../util/payUtil');
var callFuncUtil = require('../util/callFuncUtil');
var rpcFunc = require('../rpcSrv/rpcFunc.js');
var ItbCollectModel = require('../../../common/mysql/mapping/ItbCollectModel');

var async = require( 'async'); // 同步控制

// 统一返回
function ret_func(success, msg, data, res){
    var obj = {
        success: success,
        msg: msg,
        data: data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
}

//------------------------------------------------------------------
/* 意见反馈.
 * 方式:POST
 * 对应老接口: /users/feedback
 * 参数:device: 请求来源
 * 参数:uuid: 设备唯一标识
 * 参数:userId: 用户唯一标识
 * 参数:text: 意见反馈文字信息
 * 参数:images: 意见反馈添加截图的 url 数组的 json 字符串
 * 参数:deviceDesc: 意见反馈用户选填的设备信息
 * 参数:deviceInfo: app 自动收集的设备信息的字典的 json 字符串
 * {“deviceType”: “iPhone 5s”, “systemVersion”: “iOS 9.3.5”, “appVersion”: “5.1.0”,}
 * 参数:mail: 邮箱地址
 * 返回结果: {"success":1,"msg":"成功","data":{}}
 * */
function feedback_v5_1(req, res, next) {
    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.userId || req.query.userId || '0');
    var text = req.body.text || req.query.text || '';
    var images = req.body.images || req.query.images || '';
    var deviceDesc = req.body.deviceDesc || req.query.deviceDesc || '';
    var deviceInfo = req.body.deviceInfo || req.query.deviceInfo || '';
    var mail = req.body.mail || req.query.mail || '';

    // return function
    function ret_func(success, msg, id){
        var obj = {
            success:success,
            msg:msg,
            data:{id: id}
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var entity = new ItbFeedbackModel({
        advice: text,
        images: images,
        device_info_user: deviceDesc,
        device_info_sys: deviceInfo,
        mail: mail,
        user_id: userId,
        update_by: userId
    });

    entity.saveToDB(function(error, id){
        // process error
        if(error){
            console.log('users.js[feedback_v5_1] Ins Err: '+error);
            return ret_func(0,CODE.OPERATION_FAILED);
        }
        // process success
        return ret_func(1,CODE.OPERATION_SUCCESS,id);
    });

}
router.get('/feedback_v5_1', feedback_v5_1);
router.post('/feedback_v5_1', feedback_v5_1);


//------------------------------网页端 getUserInfo 模拟接口 ------------------------------
/**
 * 参数: device	"0 表示从pc来的请求
 1 表示ios
 2 表示android
 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 3 标识app 嵌入网页
 4 标识网站 web 端"
 参数: userId	 用户唯一标识
 返回结果	"{
    "success":1,
    "msg":"成功",
    "data":{
        "userId":1055,
        "userType":1,
        "mobile":13297922921,
        "registerUUID":"QWERTYUIOP-iOS",
        "nickName":"哈哈",
        "headUrl":"http://www.itbour.com/header/xxx.png",
        "userSign":"我就是不写签名咋地了",
    }
}"
 返回值与 /users/loginByPlatformUser 返回值结构保持一致
 svn://192.168.31.250:9999/design/dev/api 文档/app/LoginRegister.docx

 平台字段表: svn://192.168.31.250:9999/design/dev/api 文档/app/LoginRegister.pages
 测试地址: http://localhost:3000/v5/users/getUserInfo_v5_2?device=4&userId=128685
 */
// todo 模拟接口, 待实现, begin
function getUserInfo_v5_2 (req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, "userId");
    if(userId <= 0) {
        return ret_func(0, "userId 错误", {}, res);
    }

    //var data = {"userId":128685,"mobile":18256276313,"accessory":[{"field1":"o07tHv8t_vQhJ_3o3YLaKrNKK-os","field2":"oi9hmuFowWtUDGHePAqOZyUP2fy4","field3":"","field4":"","platform":1,"field5":"","headerUrl":"http:\/\/wx.qlogo.cn\/mmopen\/RR3bx1SuyxqSndn8HIOmlGreDe5gHrOGib4avvvZA7P3JXbrTRdMNVcjo3xA1vpbvXa62ZSux5lib8dM3Lo3XSuic1vyzPq6rmY\/0","nickName":"二狗子"}],"userSign":"","headerUrl":"http:\/\/wx.qlogo.cn\/mmopen\/RR3bx1SuyxqSndn8HIOmlGreDe5gHrOGib4avvvZA7P3JXbrTRdMNVcjo3xA1vpbvXa62ZSux5lib8dM3Lo3XSuic1vyzPq6rmY\/0","userType":1,"registerUUID":"B549E141-38A6-42C6-85FD-AFD68CC81A05-iOS","nickName":""};
    //return ret_func(1, CODE.OPERATION_SUCCESS, data, res);
    (new ItbUserModel()).findBriefUserInfo(userId, function(error, result){
       if(error || !result) {
           return usersUtil.ret_func_json(0, '用户不存在', {}, res);
       }
       result.nickName = result.nickName || "";
       result.headUrl = result.headUrl || "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/app/default_head.png";
       return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, result, res);

    });
}
router.get('/getUserInfo_v5_2', getUserInfo_v5_2);
router.post('/getUserInfo_v5_2', getUserInfo_v5_2);
// todo 模拟接口, 待实现, end

//------------------ app 端  getUserCoupons_v5_2 模拟接口 ------------------------------------
/** 获取用户优惠券列表
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: valid	0, 获取失效优惠券, 1, 获取有效优惠券
 * 参数: pageNum	请求页页码, 从0开始
 * 参数: pageSize	请求页大小
 * 返回值:
     {
        "success":1,
        "msg":"成功",
        "data":{
            "coupons":[
                {
                    "id":986, // 优惠券唯一标识
                    "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
                    "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
                    "discount_desc":"5.0元",// 优惠券额度, 5元 8折
                    "trade_type":20, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
                    "expiry_time":"2017-03-05", // 优惠券过期时间
                    "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
                    "reason":"" // 优惠券失效原因, 未失效则为空字符串
                }
            ]
        }
     }
 *
 * 测试地址: http://localhost:3000/v5/users/getUserCoupons_v5_2?device=1&userId=128685&valid=1&pageNum=0&pageSize=10&withTotalPage=1
 * */
// todo 模拟接口, 待实现, begin
function getUserCoupons_v5_2 (req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum');
    var pageSize = checkUtil.numberFromReq(req, 'pageSize');
    var valid = checkUtil.numberFromReq(req, 'valid');// 默认0
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage') || 0;
    if(userId == 0) {
        return ret_func(0, '用户 id 非法', {}, res);
    }
    if(pageSize == 0) {
        pageSize = 12;// 默认值
    }
    //var data = null;
    //if(valid) {
    //    data = {"coupons":[{"id":986,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":10,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":""},{"id":986,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":30,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":""}]};
    //} else {
    //    data = {"coupons":[{"id":987,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":10,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":"已过期"},{"id":988,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":30,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":"已使用"}]};
    //}

    //return ret_func(1, CODE.OPERATION_SUCCESS, data, res);

    printUtil.getUserCoupons_v5_2(userId, valid, pageNum, pageSize, function (error, data) {
        if (error) {
            console.log('v5/users.js getUserCoupons_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(!withTotalPage) {
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:data||[]}, res);
        }

        printUtil.getUserCouponsCnt_v6_1(userId, valid, function(err, cnt){
            if (error) {
                console.log('v5/users.js getUserCoupons_v5_2 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            var ret = {
                coupons:data||[],
                totalPage : (Math.floor((cnt-1)/pageSize)+1)
            };
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, ret, res);
        });
    });
}
router.get('/getUserCoupons_v5_2', getUserCoupons_v5_2);
router.post('/getUserCoupons_v5_2', getUserCoupons_v5_2);
// todo 模拟接口, 待实现, end

//-----------------------------app 端 getCouponByCode_v5_2 模拟接口----------------------------------
/** 兑换优惠券
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: code	 兑换码
 *
 * 返回值:
     {
        "success":1,
        "msg":"成功",
        "data":{
                "id":986, // 优惠券唯一标识
                "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
                "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
                "discount_desc":"5.0元",// 优惠券额度, 5元 8折
                "trade_type":10, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
                "expiry_time":"2017-03-05", // 优惠券过期时间
                "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
                "reason":"" // 优惠券失效原因, 未失效则为空字符串
        }
     }
 * 测试地址: http://localhost:3000/v5/users/getCouponByCode_v5_2?device=1&userId=128685&code=qwert
 * */
// todo 模拟接口, 待实现, begin
function getCouponByCode_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var code = checkUtil.stringFromReq(req, 'code');
    if(userId == 0) {
        return ret_func(0, '用户 id 非法', {}, res);
    }
    if(!code || code.length==0) {
        return ret_func(0, 'code 错误', {}, res);
    }

    //var data = {"id":986,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":20,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":""};
    //return ret_func(1, CODE.OPERATION_SUCCESS, data, res);

    printUtil.getCouponByCode_v5_2(userId, code, function (error, data) {
        if (error) {
            console.log('v5/users.js getCouponByCode_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(data.reason && data.reason.length) {
            // 注意: 兑换结束调用了: printUtil.genCouponRetInfo 组织数据, 由于个人中心页面返回错误原因最多三个字, 所以此处重新组织
            var reason = data.reason;
            if(reason == '已过期') {
                reason = "优惠码已过期";
            } else if (reason == '已领取') {
                reason = '优惠码已使用';
            } else if (reason == '已兑换') {
                reason = '优惠码已使用';
            } else if (reason == '使用中') {
                reason = '优惠码已使用';
            } else if (reason == '已使用') {
                reason = '优惠码已使用';
            }
            return printUtil.ret_func_json(0,reason,{},res);
        }
        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getCouponByCode_v5_2', getCouponByCode_v5_2);
router.post('/getCouponByCode_v5_2', getCouponByCode_v5_2);
// todo 模拟接口, 待实现, end


/**
 * 获取用户订单列表
 *
 * 参数: device	 0表示从pc来的请求/1表示ios/2表示android/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios/3 标示app 嵌入网页
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderType	商品订单: 10   发票订单: 20
 * 参数: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
 * 参数: pageNum	请求页
 * 参数: pageSize	请求页大小
 * todo 参数[可选] withTotalPage	 是否获取总页数, 默认为0, 不显示
 * 返回：
 * 	{
 * 	    "success":1,
 * 	    "msg":"成功",
 * 	    "data":{
 * 	        "orders":[
 * 	            {
 * 	                "orderId":123456789,
 * 	                "orderNo":"QGFTNNKKDLLJ",
 * 	                "state":70,
 * 	                "totalDesignFee":50,
 * 	                "totalMailFee":50,
 * 	                "totalFee":300,
 * 	                "productInfo":[
 * 	                    {
 * 	                        "id":345,
 * 	                        "thumb":"http://oss-image.jpg",
 * 	                        "qty":2,
 * 	                        "productFee":200,
 * 	                        "title":"商品名",
 * 	                        "desc":"300G白卡亚模",
 * 	                        "price":100,
 * 	                        "priceCount":2,
 * 	                        "size":"A4大小(45x64)",
 * 	                        "unit":"张",
 * 	                        "printParaId":989,
 * 	                        "detailOrderId":1
 * 	                    }
 * 	                ]
 * 	            }
 * 	        ]
 * 	        todo currentPage
 * 	        todo totalPage
 * 	    }
 * 	}
 *
 * 	测试地址: http://localhost:3000/v5/users/getUserOrderList_v5_2?device=1&uuid=1&userId=128685&pageNum=0&pageSize=10&orderType=10&withTotalPage=1
 * 	原接口地址: /print/getOrderList
 *
 *
 * */
// todo 新增方法, 待审核, begin
function getUserOrderList_v5_2(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderType = checkUtil.numberFromReq(req, 'orderType');
    if(!orderType) {
        return printUtil.ret_func_json(0,CODE.ORDER_TYPE_EMPTY,{},res);
    }
    var states = checkUtil.stringFromReq(req, 'states');
    if(states) {
        states = JSON.parse(states);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage');


    printUtil.getPrintOrderList(userId, states,pageNum,pageSize, function(error,data){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        var ret = {orders : data, currentPage : pageNum};
        // 不需要总页数
        if(!withTotalPage) {
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
        }
        // 获取总页数
        printUtil.getPrintOrderListCnt(userId, states, function(error, count){
            if(error){
                console.log(error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            ret.totalPage = Math.floor((count-1)/pageSize)+1;
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
        });
    });
}
router.get('/getUserOrderList_v5_2', getUserOrderList_v5_2);
router.post('/getUserOrderList_v5_2', getUserOrderList_v5_2);
// todo 新增方法, 已实现 待审核, begin

/**
 * 获取当前用户的环信信息
 * @param device
 * @param userId
 * 返回:
 * {“success”:1,"msg":"成功","data":{
 *  “hxUserName":"tttt", // 用户名, 英文字母和数字, 1k 以内不支持大小写
 *  “hxPassword”:"hxttt" // 密码暂无限制
 * }}
 */
function getUserHxInfo(req, res, next){
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId || userId == 0) {
        return usersUtil.ret_func_json(0, '无效用户', {}, res);
    }

    usersUtil.getUserHxInfo(userId, function(err, ret){
        if(err) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, ret, res);
    });
}
router.get('/getUserHxInfo', getUserHxInfo);
router.post('/getUserHxInfo', getUserHxInfo);

/**
 * 获取客服的环信 id
 * @param device
 * @param userId: 用户唯一标识
 * @param hxId:   用户环信 id
 * 返回:
 * {"success":1,"msg":"成功","data":{"serviceId":996}}
 */
function getHxServiceId(req, res, next){
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var hxId = checkUtil.stringFromReq(req, 'hxId');
    if(!userId || userId == 0) {
        return usersUtil.ret_func_json(0, '无效用户', {}, res);
    }

    usersUtil.getHxServiceId(userId, hxId, function(err, ret){
        if(err) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, ret, res);
    });
}
router.get('/getHxServiceId', getHxServiceId);
router.post('/getHxServiceId', getHxServiceId);

// todo 新增方法 待审核 begin
/**
 * 参数: device	"0表示从pc来的请求
 * 1表示ios
 * 2表示android
 * 101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标示app 嵌入网页"
 * 参数: userId	用户唯一标识
 * 参数: clientVer	 iOS/android/网页端版本号
 * */
// 测试地址: http://localhost:3000/v5/users/randomUserCoupon_v5_2?device=1&userId=1&clientVer=5.0
function randomUserCoupon_v5_2(req, res, next){
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var clientVer = checkUtil.numberFromReq(req, 'clientVer');

    if(!userId || userId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    // 随机获取抽奖数量
    var maxCnt = Math.round(Math.random()*3);
    callFuncUtil.getRandomCouponFromCache(20, 0, maxCnt, function(error, codes){
        if(error) {
            console.log('users.js [randomUserCoupon_v5_2] getRandomCouponFromCache err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        // 过滤优惠码空值
        codes = codes.filter(function(n){if(n == null || n == undefined || n.length == 0) {return false;}return true;});
        // 批量兑换
        if(codes && codes.length > 0) {
            printUtil.bindUserCouponByCodes_v5_2(userId, codes, function(error1, result){
                if(error1) {
                    return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {coupons:[]}, res);
                }
                return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {coupons:result}, res);
            });
        } else {
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {coupons:[]}, res);
        }
    });
}
router.get('/randomUserCoupon_v5_2', randomUserCoupon_v5_2);
router.post('/randomUserCoupon_v5_2', randomUserCoupon_v5_2);

// todo 新增方法 待审核 end



/**获取个人中心数据
 * 参数:device	0表示从p0 表示从pc来的请求
 *              1 标识一键生成iOS端
 *              2 标识一键生成android端
 *              3  标识一键生成 app 嵌入网页
 *              4 标识一键生成 web 端
 *              5 标识一键生成微信端
 *              101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 *              201 标识利楚商务
 *              301 标识酒单网
 * 参数: userId	用户唯一标识
 * 参数: productCnt	 一次获取用户文档个数 (如果<=0则不获取用户文档)
 * 参数: timestamp 	接口查询此时间戳之后的活动广播 "2016-05-17 00:00:00" (19位年月日十分秒)
 * 返回：
 *                                   {
 *                                      "success":1,
 *                                      "msg":"成功",
 *                                      "data":{
 *                                          "products":[
 *                                              {
 *                                                  "id":1615,
 *                                                  "thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U128685/2017/03/22/190902283_E6lEvjIQ3qvZFtcJRvpo/0.jpg",
 *                                                  "title":"虚构",
 *                                                  "typeL":4,
 *                                                  "time":"2017-03-22 19:09"
 *                                              }
 *                                          ],
 *                                          "broadcast":[
 *                                              {
 *                                                  "title":"广播标题",
 *                                                  "message":"消息内容",
 *                                                  "url":"http://www.itbour.com",
 *                                                  "create_time":"2016-05-17 00:00:00"
 *                                              }
 *                                          ],
 *                                          "notifications":[
 *                                              {
 *                                                  "title":"系统通知",
 *                                                  "message":"感谢您的意见反馈",
 *                                                  "url":"http://www.itbour.com",
 *                                                  "create_time":"2016-05-17 00:00:00"
 *                                              }
 *                                          ]
 *                                      }
 *                                  }
 * */
// 测试地址: http://localhost:3000/v5/users/getUserPersonalCenterInfo?device=1&userId=128729&productCnt=5&timestamp=20170113003000
function getUserPersonalCenterInfo(req, res, next){
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var productCnt = checkUtil.numberFromReq(req, 'productCnt') || 0;
    var timestamp = checkUtil.stringFromReq(req, 'timestamp');
    var states = checkUtil.stringFromReq(req, 'states');

    if(!userId || userId == 0) {
        return printUtil(1, '参数错误', {});
    }

    if(productCnt>0) {
        // 获取几个用户文档
        usersUtil.get_UserDocs(userId, 0, 0, productCnt, function(error, products) {
            if (error) {
                console.log(error);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            // 获取广播和系统通知
            usersUtil.getBroadcastAndNotifications(userId, timestamp, states, function(error, data){
                if(error) {
                    console.log('/v5/users.js [getUserPersonalCenterInfo] err: ' + error);
                    return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                }
                // 将data中的coreStructure转换为对象
                return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, { products:products, broadcast:data.broadcast, notifications:data.notifications }, res);
            });
        });
    } else {
        // 仅获取广播和系统通知
        usersUtil.getBroadcastAndNotifications(userId, timestamp, states, function(error, data){
            if(error) {
                console.log('/v5/users.js [getUserPersonalCenterInfo] err: ' + error);
                return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            // 将data中的coreStructure转换为对象
            return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, { products:[], broadcast:data.broadcast, notifications:data.notifications }, res);
        });
    }

}
router.get('/getUserPersonalCenterInfo', getUserPersonalCenterInfo);
router.post('/getUserPersonalCenterInfo', getUserPersonalCenterInfo);

//==========================================收藏相关=====================================================
/**
 * 获取用户收藏列表
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 *1 标识一键生成iOS端
 *2 标识一键生成android端
 *3  标识一键生成 app 嵌入网页
 *4 标识一键生成 web 端
 *5 标识一键生成微信端
 *
 *101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 *201 标识利楚商务
 *301 标识酒单网"
 *参数: userId	用户唯一标识
 *参数: pageNum	 请求页码
 *参数: pageSize	 请求页容量
 *参数[可选]: withTotalPage	 总页数, 0 标识不获取, 1 标识获取, 不传默认为0
 *返回结果	{
 *   "success":1,
 *   "msg":"成功",
 *   "data":{
 *       "list":[
 *           {
 *               "thumb":"http://xxx.jpg",
 *               "id":788,
 *               "typeL":1,
 *               "name" : "快递开业通知模板",
 *               "typeDesc":"名片",
 *               “author":"by乌头马角工作室",
 *               "time" : "2016-12-05 13:38"  // 收藏时间
 *           }
 *       ],
 *       "totalPage" : 1,
 *       "pageNum" :0
 *   }
 * }
 *
 *  测试地址: http://localhost:3000/v5/users/getUserCollectList_v5_4?device=1&userId=299171&pageNum=0&pageSize=12
 * */
// todo 新增接口, 待实现 begin
function getUserCollectList_v5_4(req, res, next) {

    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage') || 0;

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    usersUtil.get_userCollectList_v5_4(userId, pageNum, pageSize, function(error, list){
        if(error) {
            console.log('/v5/users.js [getUserCollectList_v5_4] request collect list err: ' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        var data = {
            pageNum : pageNum,
            list : list || []
        };
        // 不需要总页数, 提前返回
        if(withTotalPage != 1) {
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
        }
        // 请求总页数
        usersUtil.get_userCollectListCnt_v5_4(userId, function(err, count){
            if(err) {
                console.log('/v5/users.js [getUserCollectList_v5_4] request collect count err: ' + err);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            data.totlaPage = Math.floor((count-1)/pageSize)+1;
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
        });
    });
}
router.get('/getUserCollectList_v5_4', getUserCollectList_v5_4);
router.post('/getUserCollectList_v5_4', getUserCollectList_v5_4);
// todo 新增接口, 待实现 end

//--------------------------------------------------------------------------------
/**
 * 用户添加收藏项目
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: id	 模板/商品唯一标识
 * 参数: typeL	 一级分类
 *
 *  测试地址: http://localhost:3000/v5/users/userCollectItem_v5_4?device=1&userId=299171&id=4184&typeL=3
 * */
// todo 新增接口, 待实现 begin

function userCollectItem_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var id = checkUtil.numberFromReq(req, 'id');
    var typeL = checkUtil.numberFromReq(req, 'typeL');

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    if(id == 0) {
        return usersUtil.ret_func_json(0, 'id 为空', {}, res);
    }
    /**
     // 1 海报  2 多页  3 ppt.  4. 印品  6.社交媒体
     CONFIG.DOC_TYPE_1 = 1;
     CONFIG.DOC_TYPE_2 = 2;
     CONFIG.DOC_TYPE_3 = 3;
     CONFIG.DOC_TYPE_4 = 4;
     CONFIG.DOC_TYPE_6 = 6;
     * */
    if( typeL != CONFIG.DOC_TYPE_1 &&
        typeL != CONFIG.DOC_TYPE_3 &&
        typeL != CONFIG.DOC_TYPE_4 &&
        typeL != CONFIG.DOC_TYPE_6 &&
        typeL != CONFIG.DOC_TYPE_7 &&
        typeL != CONFIG.DOC_TYPE_8)
    {
        return usersUtil.ret_func_json(0, 'type 错误', {}, res);
    }

    // 确认收藏项目的合法性
     usersUtil.chk_userCollectItemValid_v5_4(typeL, userId, id, function(error, result){
         if(error) {
             console.log('/v5/users/ [userCollectItem_v5_4] chk collectItem error: ' + error);
             return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
         }
         // 商品下架, 模板下架等
         if(result.canCollect != 1) {
             return usersUtil.ret_func_json(0, '该项目暂时无法收藏', {}, res);
         }

         if(result.isCollected == 1) {
             return usersUtil.ret_func_json(1, '您已收藏过该项目', {}, res);
         }

         // 覆盖/忽略重复插入
        usersUtil.insertUserCollect_v5_4(typeL, userId, result.tmpl_id, result.item_id || null, function(err, result){
            if(err) {
                console.log('/v5/users/ [userCollectItem_v5_4] collect error: ' + err);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }

            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
        });
     });
}
router.get('/userCollectItem_v5_4', userCollectItem_v5_4);
router.post('/userCollectItem_v5_4', userCollectItem_v5_4);

// todo 新增接口, 待实现 end


//--------------------------------------------------------------------------------
/**
 * 用户删除收藏项目
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: id	 模板/商品唯一标识
 * 参数: typeL	 一级分类
 *
 * 测试地址: http://localhost:3000/v5/users/removeUserCollect_v5_4?device=1&userId=299171&id=714&typeL=6
 * */
// todo 新增接口, 待实现 begin

function removeUserCollect_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var id = checkUtil.numberFromReq(req, 'id');
    var typeL = checkUtil.numberFromReq(req, 'typeL');

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    if(id == 0) {
        return usersUtil.ret_func_json(0, 'id 为空', {}, res);
    }
    /**
     // 1 海报  2 多页  3 ppt.  4. 印品  6.社交媒体
     CONFIG.DOC_TYPE_1 = 1;
     CONFIG.DOC_TYPE_2 = 2;
     CONFIG.DOC_TYPE_3 = 3;
     CONFIG.DOC_TYPE_4 = 4;
     CONFIG.DOC_TYPE_6 = 6;
     * */
    if( typeL != CONFIG.DOC_TYPE_1 &&
        typeL != CONFIG.DOC_TYPE_3 &&
        typeL != CONFIG.DOC_TYPE_4 &&
        typeL != CONFIG.DOC_TYPE_6 &&
        typeL != CONFIG.DOC_TYPE_7 &&
        typeL != CONFIG.DOC_TYPE_8)
    {
        return usersUtil.ret_func_json(0, 'type 错误', {}, res);
    }

    usersUtil.removeUserCollect_v5_4(typeL, userId, id, function(error, result){
        if(error) {
            console.log('/v5/users/ [removeUserCollect_v5_4] collect error: ' + err);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
    });

}
router.get('/removeUserCollect_v5_4', removeUserCollect_v5_4);
router.post('/removeUserCollect_v5_4', removeUserCollect_v5_4);

// todo 新增接口, 待实现 end

//--------------------------------------------------------------------------------
/**
 * 确认用户是否收藏项目
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: id	 模板/商品唯一标识
 * 参数: typeL	 一级分类
 *
 * 测试地址: http://localhost:3000/v5/users/checkCollected_v5_4?device=1&userId=128729&id=1&typeL=1
 * */
// todo 新增接口, 待实现 begin

function checkCollected_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var id = checkUtil.numberFromReq(req, 'id');
    var typeL = checkUtil.numberFromReq(req, 'typeL');

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    if(id == 0) {
        return usersUtil.ret_func_json(0, 'id 为空', {}, res);
    }
    /**
     // 1 海报  2 多页  3 ppt.  4. 印品  6.社交媒体
     CONFIG.DOC_TYPE_1 = 1;
     CONFIG.DOC_TYPE_2 = 2;
     CONFIG.DOC_TYPE_3 = 3;
     CONFIG.DOC_TYPE_4 = 4;
     CONFIG.DOC_TYPE_6 = 6;
     * */
    if( typeL != CONFIG.DOC_TYPE_1 &&
        typeL != CONFIG.DOC_TYPE_3 &&
        typeL != CONFIG.DOC_TYPE_4 &&
        typeL != CONFIG.DOC_TYPE_6 &&
        typeL != CONFIG.DOC_TYPE_7 &&
        typeL != CONFIG.DOC_TYPE_8)
    {
        return usersUtil.ret_func_json(0, 'type 错误', {}, res);
    }

    // 确认收藏项目的合法性
    usersUtil.chk_userCollectItemValid_v5_4(typeL, userId, id, function(error, result) {
        if (error) {
            console.log('/v5/users/ [userCollectItem_v5_4] chk collectItem error: ' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_SUCCESS, {}, res);
        }
        // 商品下架, 模板下架等
        if(result.canCollect != 1) {
            console.log('/v5/users.js [checkCollected_v5_4] warning:用户收藏项目已下架===>  type: ' + typeL + ' id: ' + id + ' userId: ' +userId)
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {isCollected : result.isCollected || 0}, res);
    });
}
router.get('/checkCollected_v5_4', checkCollected_v5_4);
router.post('/checkCollected_v5_4', checkCollected_v5_4);

// todo 新增接口, 待实现 end

//==========================================城市合伙人相关=====================================================
/**
 * 获取城市合伙人状态信息
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 *
 * 测试地址: http://localhost:3000/v5/users/getCityPartnerInfo_v5_4?device=1&userId=128729
 * */
// todo 新增接口, 待实现 begin
function getCityPartnerInfo_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }

    usersUtil.getCityPartnerInfo_v5_4(userId, function(error, result){
        //异常保护
        if (error) {
            console.log('/v5/users/ [getCityPartnerInfo_v5_4] chk collectItem error: ' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_SUCCESS, {}, res);
        }

        if(!result || result.length == 0){
            var data = {};
            data.state = -1;
            data.desc = "尚未申请合伙人";
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,data, res);
        }

        var data = {};
        data.state = result[0].state;
        data.desc = result[0].desc || '';
        //完成状态
        if(result[0].state != 40){
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,data, res);
        }
        usersUtil.getCityPartnermessage_v5_4(userId, function(error, result01){
            //异常保护
            if (error) {
                console.log('/v5/users/ [getCityPartnerInfo_v5_4] chk collectItem error: ' + error);
                return usersUtil.ret_func_json(0, CODE.OPERATION_SUCCESS, {}, res);
            }
            if(!result01 || result01.length == 0){
                return usersUtil.ret_func_json(0, "未找到合伙人信息,数据错误", {}, res);
            }
            data.level = result01[0].level;
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,data, res);
        })

    });
}
router.get('/getCityPartnerInfo_v5_4', getCityPartnerInfo_v5_4);
router.post('/getCityPartnerInfo_v5_4', getCityPartnerInfo_v5_4);
// todo 新增接口, 待实现 end
//--------------------------------------------------------------------------------
/**
 * 提交城市合伙人申请
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端

 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: info	"{
 *	"name" : "大板凳",
 *	"cityInfo" : {
 *		"prov" : {"id" : 3022,
 *			"text" : "湖北省"},
 *		"city" : {"id" : 3022,
 *			"text" : "武汉市"},
 *		"dist" : {"id" : 3022,
 *			"text" : "洪山区}
 *	},
 *	"bank" : "中国人民银行",
 *	"bankAccount" : 99999988888777777
 * }"
 *
 * p_userId 为城市合伙人id
 *
 * 测试地址: http://localhost:3000/v5/users/commitCityPartnerInfo_v5_4?device=1&userId=128729&info={"name":"大板凳","cityInfo":{"prov":{"id":3022,"text":"湖北省"},"city":{"id":3022,"text":"武汉市"},"dist":{"id":3022,"text":"洪山区"},"detail":"啦啦啦啦啦啦啦啦啦"},"bank":"汉口银行","bankAccount":1234567890112345600}
 * */
// todo 新增接口, 待实现 begin
function commitCityPartnerInfo_v5_4(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var info = checkUtil.stringFromReq(req, 'info');
    var p_userId = checkUtil.stringFromReq(req, 'p_userId');

    //参数判断
    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    if(!info || info.length == 0) {
        return usersUtil.ret_func_json(0, 'info 为空', {}, res);
    }
    console.log("/commitCityPartnerInfo_v5_4v5/users/ --> info: " + info);
    info = JSON.parse(info);
    if(!info || info == null || typeof info == 'undefined') {
        return usersUtil.ret_func_json(0, 'info 有误', {}, res);
    }

    usersUtil.commit_cityPartnerInfo_v5_4(userId,info,3600,p_userId,function(error, result){
        //异常保护
        if (error) {
            console.log('/v5/users/ [commitCityPartnerInfo_v5_4] chk collectItem error: ' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_SUCCESS, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,{}, res);
    })
}
router.get('/commitCityPartnerInfo_v5_4', commitCityPartnerInfo_v5_4);
router.post('/commitCityPartnerInfo_v5_4', commitCityPartnerInfo_v5_4);
// todo 新增接口, 待实现 end
//--------------------------------------------------------------------------------

/**
 *查看领券用户
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 * 参数[可选]: withTotalPage	默认为0 , 标识不获取总页数, 1, 为获取总页数
 {
     "success":1,
     "msg":"成功",
     "data":{
         "list":[
             {
                 "time":"04-23",
                 “mobile":"133****2222",
                 “couponState":1,  // 优惠券状态
                 “orderState":0      //  订单状态
             }
         ],
        "pageNum" : 0,
	    "totalPage" : 1
     }
 }
 http://localhost:3000/v5/users/getPartnerCouponUsers_v5_4?device=1&userId=1&pageNum=0&pageSize=10&withTotalPage=1
 * */

function getPartnerCouponUsers_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage') || 0;

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }

    usersUtil.getPartnerCouponUsers_v5_4(userId, pageNum, pageSize, withTotalPage, function(error, data){
        if (error) {
            console.log('v5/users.js getPartnerCouponUsers_v5_4 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });

}
router.get('/getPartnerCouponUsers_v5_4', getPartnerCouponUsers_v5_4);
router.post('/getPartnerCouponUsers_v5_4', getPartnerCouponUsers_v5_4);

/*
 * 查询合伙人订单列表
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数[可选]: startDt  开始时间戳 如: 2017-05-01
 * 参数[可选]: endDt    截止时间戳 如: 2017-05-30
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 *  参数[可选]: withTotalPage	默认为0 , 标识不获取总页数, 1, 为获取总页数
 *
 {
    "list" : [
        {
            "orderId" : 456
            "time" : “2017-05-03”, //  订单日期
            “mobile”: “188****4928”, // 订单手机号
            "orderAmount" : 68,  // 订单金额
            "orderIncome" : 20 // 订单收益
        }
    ],
    "pageNum" : 9,
    "totalPage" : 1
 }
 http://localhost:3000/v5/users/getIncomeOrderList_v5_4?device=1&userId=1&pageNum=0&pageSize=10
 * */
// todo 新增接口, 待实现 begin
function getIncomeOrderList_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage') || 0;

    var startDt = checkUtil.stringFromReq(req, 'startDt');
    var endDt = checkUtil.stringFromReq(req, 'endDt');

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }

    //var data = {"list":[{"orderId":456,"time":"2017-05-03","mobile":"188****4928","orderAmount":68,"orderIncome":20}],pageNum:0,totalPage:1};
    //return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);

    usersUtil.getIncomeOrderList_v5_4(userId, startDt, endDt, pageNum, pageSize, withTotalPage, function(error, data){
        if (error) {
            console.log('v5/users.js getIncomeOrderList_v5_4 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getIncomeOrderList_v5_4', getIncomeOrderList_v5_4);
router.post('/getIncomeOrderList_v5_4', getIncomeOrderList_v5_4);
// todo 新增接口, 待实现 end
//--------------------------------------------------------------------------------
/**
 * 获取城市合伙人收益到账记录
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 * 参数[可选]: withTotalPage	默认为0 , 标识不获取总页数, 1, 为获取总页数
 * {
        "partnerInfo":{
            "level": 10, // 合伙人级别：10普通、20高级
            "bacnk":"汉口银行",
            "totalIncome":9898,
            "bankAccount":987898982
        },
        "list":[
            {
                "time":"2017年5月",
                "income":98
            },
            {
                "time":"2017年4月",
                "income":90
            }
        ]
    }
 http://localhost:3000/v5/users/getPartnerIncome_v5_4?device=1&userId=128729&pageNum=0&pageSize=15
 * */
// todo 新增接口, 待实现 begin
 function getPartnerIncome_v5_4(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum');
    var pageSize = checkUtil.numberFromReq(req, 'pageSize');
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage');
    var state = 40;
    //参数判断
    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    //第三方库(async.series([方法数组],callback));
    async.series([
        //获取合伙人的收益记录列表
        function(callback){
           usersUtil.get_partnerIncome_v5_4(userId, pageNum, pageSize,withTotalPage,
               function(err, data){
                   callback(err, data);
               });
        },
        //获取合伙人信息
        function (callback) {
            usersUtil.getCityPartnermessage_v5_4(userId,
                function(err, data){
                    callback(err, data);
            });
        }
    ],function(err, results){
        if(err){
            console.log(err);
            return usersUtil.ret_func_json(0, 'error', {}, res);
        }
        var  data={
            "partnerInfo":{
                "level": results[1][0].level||0,
                "bank": results[1][0].bank || "",
                "bankAccount": results[1][0].bank_account || "",
                "totalIncome": results[0].totalIncome||0
            },
            "list":[]
        };
        for(var i=0;i<results[0].list.length;i++){
            var item = results[0].list[i];
            var para = {};
            para.time = item.year +"年"+ item.month+"月";
            para.income = item.income || 0;
            para.incomeBase = item.income_base || 0;// added v6.1
            para.incomeExtra = item.income_extra || 0;// added v6.1
            para.incomeBonus = item.income_bonus || 0;// added v6.1
            data.list.push(para);
        }
        if(results[0].totalPage){
            data.totalPage = results[0].totalPage;
        }
        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
    });
 }
router.get('/getPartnerIncome_v5_4', getPartnerIncome_v5_4);
router.post('/getPartnerIncome_v5_4', getPartnerIncome_v5_4);
// todo 新增接口, 待实现 end
//--------------------------------------------------------------------------------
/**
 * 获取城市合伙人推广链接
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 *  {
		"url" : "http://www.itbour.com/activity/coupon.html?partnerId=9098723467",
		"title" : "优惠券标题",
		"content" : "领取优惠券",
		"imageUrl" " "http://oss-itbour.com"
	}
 http://localhost:3000/v5/users/getPartnerShareInfo_v5_4?device=1&userId=128729
 * */
// todo 新增接口, 待实现 begin
function getPartnerShareInfo_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');

    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }

    // 检查合伙人
    usersUtil.isValidCityPartner(userId, function(chkErr, isValid) {
        if (chkErr) {
            console.log('users.js [getPartnerShareInfo_v5_4] isValidCityPartner err:' + chkErr);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        if(isValid) {
            var uId = parseInt(userId+187020).toString(20);// 变换userId
            var param = EncryptUtil.genSimpleEncryptInfo(uId);

            var url = 'http://www.itbour.com/shareCoupon';
            url += '?q='+param.q+'&t='+param.t+'&c='+param.c;

            rpcFunc.createQrCodeOfCityPartnerCoupon(url, function(getQrCodeErr, data){

                if(getQrCodeErr) {
                    console.log('users.js [getPartnerShareInfo_v5_4] createQrCodeOfCityPartnerCoupon err:' + getQrCodeErr + JSON.stringify(data));
                    return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                }
                return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {
                    url: url,
                    //title: '一键生成 设计印刷大礼包！',
                    title: '全场限免！快来领领领领领领领领领领领领领优惠券啦！',
                    //content: '名片、海报、ppt设计神器！输入文字内容，自动排版设计，超美模版每日更新！',
                    content: '名片、海报、宣传单一键生成神器！输入文字、自动生成！海量精美模板全场免费使用！',
                    imageUrl: 'http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U13/2017/05/17/205541498_HaRJtrbSV9l1D7nvG9qw',
                    promotionCode : data
                }, res);
            });



        } else {
            return usersUtil.ret_func_json(0, '无效用户', {}, res);
        }
    });
}
router.get('/getPartnerShareInfo_v5_4', getPartnerShareInfo_v5_4);
router.post('/getPartnerShareInfo_v5_4', getPartnerShareInfo_v5_4);
// todo 新增接口, 待实现 end
//----------------------------------------------------------------------------------
/**
 * 参与城市合伙人发起的推广链接获取优惠券
 *
 * 参数: id	 合伙人活动唯一标识(合伙人userId)
 * 参数: mobile	 领取人手机号
 *{
        "coupons":[
            {
                "id":986,
                "code":"QWERTPOIUYEV",
                "type_desc":"抵扣券",
                "discount": 500,
                "discount_desc":"5.0元",
                "trade_type":20,
                "expiry_time":"2017-03-05",
                "coupon_desc":"暂不抵扣运费",
                "reason":""
            }
        ],
        "errMsg":"" // 正常流程下为空
    }
 http://localhost:3000/v5/users/getPartnerCoupons_v5_4?device=1&id=1&mobile=18872202619
 * */
// todo 新增接口, 待实现 begin
function getPartnerCoupons_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var id = checkUtil.numberFromReq(req, 'id');
    if(id <= 0) {
        return usersUtil.ret_func_json(0, 'Id 为空', {}, res);
    }
    var mobile = checkUtil.numberFromReq(req, 'mobile');
    if(mobile <= 0) {
        return usersUtil.ret_func_json(0, 'Mobile 为空', {}, res);
    }

    // 检查合伙人
    usersUtil.isValidCityPartner(id, function(chkErr, isValid) {
        if(chkErr) {
            console.log('users.js [getPartnerCoupons_v5_4] isValidCityPartner err:' + chkErr);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        if(isValid) {
            // 检查手机号
            usersUtil.chkCouponByMobile(mobile, null, function(chkErr2, bHas) {
                if(chkErr2) {
                    console.log('users.js [getPartnerCoupons_v5_4] chkCouponByMobile err:' + chkErr2);
                    return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                }

                if(!bHas) {
                    // 抽印品优惠券
                    callFuncUtil.getCouponFromCache(30/*城市合伙人用(印品)*/, 2/*2张*/, function(error, codes){
                        if(error) {
                            console.log('users.js [getPartnerCoupons_v5_4] getCouponFromCache(30) err:' + error);
                            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                        }
                        // 抽vip优惠券
                        callFuncUtil.getCouponFromCache(31/*城市合伙人用(vip)*/, 1/*1张*/, function(error2, codes2){
                            if(error2) {
                                console.log('users.js [getPartnerCoupons_v5_4] getCouponFromCache(31) err:' + error2);
                                return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                            }
                            // 抽logo优惠券
                            callFuncUtil.getCouponFromCache(32/*城市合伙人用(logo)*/, 1/*1张*/, function(error3, codes3) {
                                if (error3) {
                                    console.log('users.js [getPartnerCoupons_v5_4] getCouponFromCache(32) err:' + error3);
                                    return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                                }

                                // 过滤优惠码空值
                                codes = (codes||[]).concat(codes2||[]).concat(codes3||[]).filter(function(n){
                                    if(n == null || n == undefined || n.length == 0) {
                                        return false;
                                    }
                                    return true;
                                });

                                // 批量领取＋(已注册时就)兑换
                                if(codes && codes.length > 0) {
                                    usersUtil.getPartnerCoupons_v5_4(id, mobile, codes, function(err, ret){
                                        if(err) {
                                            console.log('users.js [getPartnerCoupons_v5_4] getPartnerCoupons_v5_4 err:' + err);
                                            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {coupons:[]}, res);
                                        }
                                        // 尝试加为下线
                                        usersUtil.tryAddPartnerCustom(id, mobile, function(err, pc_id){
                                            console.log('add customer to partner '+ pc_id?'success':'failed'+' ,pc_id:'+pc_id);
                                            // 不看添加下线的结果
                                            return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {coupons:ret}, res);
                                        })
                                    });
                                } else {
                                    return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {coupons:[]}, res);
                                }
                            });
                        });
                    });
                } else {
                    return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {coupons:[], errMsg:'今日已领取过优惠券'}, res);
                }
            });

        } else {
            return printUtil.ret_func_json(0, '非法用户', {}, res);
        }
    });
}
router.get('/getPartnerCoupons_v5_4', getPartnerCoupons_v5_4);
router.post('/getPartnerCoupons_v5_4', getPartnerCoupons_v5_4);
// todo 新增接口, 待实现 end

//----------------------------------------------------------------------------------
/**
 * 5-15:获取普通合伙人的信息
 *
 * 参数: device
 * 参数: userId
 {
	"success" : 1,
	"msg" : "成功",
	"data" : {
		"name" : "大板凳",
		"cityInfo" : {
			"prov" : {"id" : 3022,
				"text" : "湖北省"},
			"city" : {"id" : 3022,
				"text" : "武汉市"},
			"dist" : {"id" : 3022,
				"text" : “洪山区},
			“detail”:”光谷创业街10栋"// 地址详情
		},
		"bank" : "中国人民银行",
		"bankAccount" : 99999988888777777

	}
 }
 http://localhost:3000/v5/users/getCityPartnerInfoEx_v5_4?device=1&userId=1
 * */
// todo 新增接口, 待实现 begin
function getCityPartnerInfoEx_v5_4(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }


    // 检查合伙人
    usersUtil.getCityPartnerInfoEx_v5_4(userId, function(error, data) {
        if(error) {
            console.log('users.js [getCityPartnerInfo_v5_4] getCityPartnerInfo_v5_4 err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getCityPartnerInfoEx_v5_4', getCityPartnerInfoEx_v5_4);
router.post('/getCityPartnerInfoEx_v5_4', getCityPartnerInfoEx_v5_4);


//----------------------------------------------------------------------------------
/**
 * 5-16:更新普通合伙人的信息
 *
 * 参数: device
 * 参数: userId
 * 参数：info
    {
		"name" : "大板凳",
		"cityInfo" : {
			"prov" : {"id" : 3022,
				"text" : "湖北省"},
			"city" : {"id" : 3022,
				"text" : "武汉市"},
			"dist" : {"id" : 3022,
				"text" : “洪山区},
			“detail”:”光谷创业街10栋"// 地址详情
		},
		"bank" : "中国人民银行",
		"bankAccount" : 99999988888777777
    }
 http://localhost:3000/v5/users/updateCityPartnerInfo_v5_4
 * */
// todo 新增接口, 待实现 begin
function updateCityPartnerInfo_v5_4(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var info = checkUtil.stringFromReq(req, 'info');

    //参数判断
    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    if(!info || info.length == 0) {
        return usersUtil.ret_func_json(0, 'info 为空', {}, res);
    }

    info = JSON.parse(info);
    if(!info || info == null || typeof info == 'undefined') {
        return usersUtil.ret_func_json(0, 'info 有误', {}, res);
    }

    // 检查合伙人
    usersUtil.updateCityPartnerInfo_v5_4(userId, info, function(error) {
        if(error) {
            console.log('users.js [updateCityPartnerInfo_v5_4] updateCityPartnerInfo_v5_4 err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/updateCityPartnerInfo_v5_4', updateCityPartnerInfo_v5_4);
router.post('/updateCityPartnerInfo_v5_4', updateCityPartnerInfo_v5_4);


/**
 * 5-17: 获取高级合伙人管辖区域列表
 * @param device
 * @param userId: 高级合伙人userId
 * @return
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *   "list": [
 *     {
 *       "prov": {
 *         "id": 150000,
 *         "text": "内蒙古自治区"
 *       },
 *       "city": {
 *         "id": 150500,
 *         "text": "通辽市"
 *       },
 *       "dist": {
 *         "id": 150522,
 *         "text": "科尔沁左翼后旗"
 *       }
 *     }
 *   ]
 *  }
 * }
 */
function getCityPartnerAreaList_v5_6(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;

    //参数判断
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getCityPartnerAreaList_v5_6(userId, function(error, ret) {
        if(error) {
            console.log('users.js [getCityPartnerAreaList_v5_6] getCityPartnerAreaList_v5_6 err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {list:ret||[]}, res);
    });
};
router.get('/getCityPartnerAreaList_v5_6', getCityPartnerAreaList_v5_6);
router.post('/getCityPartnerAreaList_v5_6', getCityPartnerAreaList_v5_6);

/**
 * 5-18: 获取高级合伙人所选区域的所选时间段内该区域对应的订单的合伙人抽成列表
 * @param device
 * @param userId: 高级合伙人userId
 * @param areaInfo[可选]: {"prov":150000,"city":150500,"dist":150522} 区域列表的json字符串 (不传则标识获取所有管辖区域内的列表)
 * @param timeInfo[可选]: {"year":2017,"month":6} 时间的json字符串 (不传则标识获取成为高级合伙人以来所有收益)
 * @param pageNum
 * @param pageSize
 * @param withTotalPage[可选]: 是否获取总页数
 * @return
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *   "total":{
 *     "orderSum": 3000,
 *     "incomeSum": 30
 *   },
 *   "list": [
 *     {
 *       "partnerId" : 989,
 *       "mobile": "188****2619",
 *       "orderSum": 100,
 *       "incomeSum": 3
 *     }
 *   ],
 *  "pageNum":0,
 *  "totalPage":1
 *  }
 * }
 * 测试地址：http://localhost:3000/v5/users/filterHigherCityPartnerIncome_v5_6?device=0&userId=299174&pageNum=0&pageSize=10&withTotalPage=1&areaInfo={"prov":110000,"city":110100,"dist":110101}&timeInfo={"year":2017,"month":4}
 */
function filterHigherCityPartnerIncome_v5_6(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage')||0;
    var areaInfoStr = checkUtil.stringFromReq(req, 'areaInfo')||'';
    var timeInfoStr = checkUtil.stringFromReq(req, 'timeInfo')||'';

    //参数判断
    if(userId <= 0 || pageNum<0 || pageSize<0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    var areaInfo = null;
    if(areaInfoStr && areaInfoStr.length>0) {
        areaInfo = JSON.parse(areaInfoStr);
    }

    var timeInfo = null;
    if(timeInfoStr && timeInfoStr.length>0) {
        timeInfo = JSON.parse(timeInfoStr);
    }

    usersUtil.getHighCityPartnerExIncome_v5_6(userId, areaInfo, timeInfo,
        pageNum, pageSize, withTotalPage, function(error, ret) {
            if(error) {
                console.log('users.js [filterHigherCityPartnerIncome_v5_6] getHighCityPartnerExIncome_v5_6 err:' + error);
                return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }

            return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, ret, res);
        }
    );
};
router.get('/filterHigherCityPartnerIncome_v5_6', filterHigherCityPartnerIncome_v5_6);
router.post('/filterHigherCityPartnerIncome_v5_6', filterHigherCityPartnerIncome_v5_6);

/**
 * 5-19: 获取城市合伙人某区域内某时间段内成单明细
 * @param device
 * @param userId: 高级合伙人userId
 * @param partnerId: 指定的其它合伙人id
 * @param areaInfo[可选]: {"prov":150000,"city":150500,"dist":150522} 区域列表的json字符串 (不传则标识获取所有管辖区域内的列表)
 * @param timeInfo[可选]: {"year":2017,"month":6} 时间的json字符串 (不传则标识获取成为高级合伙人以来所有收益)
 * @param pageNum
 * @param pageSize
 * @param withTotalPage[可选]: 是否获取总页数
 * @return
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *   "list": [
 *     {
 *       "orderId": 989,// 订单id
 *       "income": 3,
 *       "mobile": "188****2619",
 *       "orderFee": 100,
 *       "time": "07-08"
 *     }
 *   ],
 *  "pageNum":0,
 *  "totalPage":1
 *  }
 * }
 * 测试地址：http://localhost:3000/v5/users/filterHigherCityPartnerIncomeDetail_v5_6?device=0&userId=299174&partnerId=5&pageNum=0&pageSize=10&withTotalPage=1&areaInfo={"prov":110000,"city":110100,"dist":110101}&timeInfo={"year":2017,"month":7}
 */
function filterHigherCityPartnerIncomeDetail_v5_6(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var partnerId = checkUtil.numberFromReq(req, 'partnerId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage')||0;
    var areaInfoStr = checkUtil.stringFromReq(req, 'areaInfo')||'';
    var timeInfoStr = checkUtil.stringFromReq(req, 'timeInfo')||'';

    //参数判断
    if(userId <= 0 || partnerId <= 0 || pageNum<0 || pageSize<0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    var areaInfo = null;
    if(areaInfoStr && areaInfoStr.length>0) {
        areaInfo = JSON.parse(areaInfoStr);
    }

    var timeInfo = null;
    if(timeInfoStr && timeInfoStr.length>0) {
        timeInfo = JSON.parse(timeInfoStr);
    }

    usersUtil.getHighCityPartnerExIncomeDetail_v5_6(userId, partnerId, areaInfo, timeInfo,
        pageNum, pageSize, withTotalPage, function(error, ret) {
        if(error) {
            console.log('users.js [filterHigherCityPartnerIncomeDetail_v5_6] getHighCityPartnerExIncomeDetail_v5_6 err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, ret, res);
    });
};
router.get('/filterHigherCityPartnerIncomeDetail_v5_6', filterHigherCityPartnerIncomeDetail_v5_6);
router.post('/filterHigherCityPartnerIncomeDetail_v5_6', filterHigherCityPartnerIncomeDetail_v5_6);


/**
 * 3-16: 获取用户地址列表
 * @param device
 * @param userId: 用户Id
 * @param pageNum: 页码, 从0开始
 * @param pageSize: 页容量
 * @return
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *   "list": [
 *     {
 *       "id": 988,
 *       "mobile": 1887220261,
 *       "name": "呵呵哒",
 *       "prov": {
 *         "id": 150000,
 *         "text": "内蒙古自治区"
 *       },
 *       "city": {
 *         "id": 150500,
 *         "text": "通辽市"
 *       },
 *       "dist": {
 *         "id": 150522,
 *         "text": "科尔沁左翼后旗"
 *       },
 *       "detail": "光谷创业街10栋",
 *       "default": 1 // 是否为默认地址
 *     }
 *   ],
 *   "pageNum": 9,
 *   "totalPage": 3
 *  }
 * }
 *
 * 测试地址: http://localhost:3000/v5/users/getUserAddressList_v5_7?device=1&userId=299188&pageNum=0&pageSize=10
 */
function getUserAddressList_v5_7(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    //参数判断
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getUserAddressList_v5_7(userId, pageNum, pageSize, function(error, retData) {
        if(error) {
            console.log('users.js [getUserAddressList_v5_7] getUserAddressList_v5_7 err:' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
    });
}
router.get('/getUserAddressList_v5_7', getUserAddressList_v5_7);
router.post('/getUserAddressList_v5_7', getUserAddressList_v5_7);

//-------------------------------------------------------------------------------------------
/**
 * 删除用户地址列表中的地址
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: ids	将要删除的地址 id 数组的 json 字符串, 如: [128,256]
 * 返回结果: 	{"success":1,"msg":"成功","data":{}}
 *
 * 测试地址: http://localhost:3000/v5/users/removeUserAddress_v5_7?device=1&userId=299188&ids=[3562,3563]
 * */

function removeUserAddress_v5_7(req, res, next) {
    var device = checkUtil.numberFromReq(req, "device");
    var userId = checkUtil.numberFromReq(req, "userId") || 0;
    var ids = checkUtil.stringFromReq(req, "ids");
    if (userId <= 0 ) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    if (ids == null || ids.length == 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    ids = JSON.parse(ids);
    if(!ids || ids.length == 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    // 1. 确认删除的是否有默认地址, 若有, 则执行第三步
    usersUtil.checkUserDefaultAddress(userId, ids, function(chkErr, defaultId){
        if(chkErr) {
            console.log('users.js [removeUserAddress_v5_7] checkUserDefaultAddress err:' + chkErr);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        // 2. 删除对应的地址
        usersUtil.removeUserAddress_v5_7(userId, ids, function(removeErr){
            if(removeErr) {
                console.log('users.js [removeUserAddress_v5_7] removeuserAddress_v5_7 err:' + removeErr);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }

            // 3. 如果有需要,重设最新的地址为默认地址
            if(!defaultId || defaultId <= 0) {
                return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res)
            }
            usersUtil.setUserLastAddressToDefault(userId, function(upErr){
                if(upErr) {
                    console.log('users.js [removeUserAddress_v5_7] removeuserAddress_v5_7 err:' + upErr);
                    return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
                }

                return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
            });
        });
    });
}
router.get('/removeUserAddress_v5_7', removeUserAddress_v5_7);
router.post('/removeUserAddress_v5_7', removeUserAddress_v5_7);

//-------------------------------------------------------------------------------------------
/**
 * 设置用户地址为默认地址
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: addressId	用户地址唯一标识
 * 参数: default	 是否设置为默认地址, 前端固定传1, 标记设置为默认地址
 *
 * 测试地址: http://localhost:3000/v5/users/setUserAddressDefault_v5_7?device=1&userId=299188&addressId=3562&isDefault=1
 * */
function setUserAddressDefault_v5_7(req, res, next) {
    var device = checkUtil.numberFromReq(req, "device");
    var userId = checkUtil.numberFromReq(req, "userId") || 0;
    var addressId = checkUtil.numberFromReq(req, "addressId") || 0;
    var isDefault = checkUtil.numberFromReq(req, "default") || 1;
    if (userId <= 0 ) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    if (addressId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.setUserAddressDefault_v5_7(userId, addressId, isDefault, function (error) {
        if(error) {
            console.log('users.js [setUserAddressDefault_v5_7] setUserAddressDefault_v5_7 err:' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/setUserAddressDefault_v5_7', setUserAddressDefault_v5_7);
router.post('/setUserAddressDefault_v5_7', setUserAddressDefault_v5_7);

/**
 * 获取最新版本信息
 * 参数: device	"0表示从p0 表示从pc来的请求
 1 标识一键生成iOS端
 2 标识一键生成android端
 3  标识一键生成 app 嵌入网页
 4 标识一键生成 web 端
 5 标识一键生成微信端

 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 201 标识利楚商务
 301 标识酒单网"
 参数: deviceInfo	"{
        "device": 2,
        "channel" : "xiaomi",
        "deviceType" : "mi 5",
        "systemVersion" : "android 5.1.0",
        "appVersion" : "5.6.0"
    }
 对象的 json 字符串"
 返回结果	"{
        "success" : 1,
        "msg" : "成功",
        "data" : {
            "lastVersion" : "5.7.0",
            "apkUrl" : "http://oss-itbour-yi-jian-sheng-cheng/5.7.0/yijianshengcheng.apk",
            "upgradeUrl" : "http://www.itbour.com/app/upgrade.html"
        }
    }"
 *
 * 测试地址: http://localhost:3000/v5/users/getLastVersion_v5_7?device=1
 * */
 function getLastVersion_v5_7(req, res, next) {

    var device = checkUtil.numberFromReq(req, 'device');
    var deviceInfo = checkUtil.stringFromReq(req, 'deviceInfo');

    usersUtil.getLastVersion_v5_7(device, function(error, result){
        if(error) {
            console.log('users.js [getLastVersion_v5_7] getLastVersion_v5_7 err:' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        // 查询到最新版本信息
        if(result) {
            var ret = {
                apkUrl : result.url,
                upgradeUrl : "http://www.itbour.com/androidDownload.html",
                lastVersion : result.ver
            };
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, ret, res);
        }

        // 查询不到
        return usersUtil.ret_func_json(0, "暂无版本", {}, res);
    });
}
router.get('/getLastVersion_v5_7', getLastVersion_v5_7);
router.post('/getLastVersion_v5_7', getLastVersion_v5_7);


//------------------------------------------------------------------------------------------------
/**
 * 1-21: 获取用户预填信息内容
 *
 * 参数:device  请求来源
 * 参数:userId  用户唯一标识
 * 参数:type    信息类型: 10用户资料(默认), 20公司资料
 *
 * 返回值:
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *    "autoFill":1,// 是否自动填充
 *    "tmplFlg":1,// 当用户未曾填写时, tmplFlg 为1, 标记是模版数据
 *    "datum" : {xxxxx},// SJGTGV3结构
 *    "version": 3,// 提纲结构版本号
 *    "updCnt": 1// 版本号内提纲模版修改次数
 *  }
 * }
 *
 * 测试地址: http://localhost:3000/v/users/getUserDatumInfo_v6_0?device=1&uuid=1&userId=299188&type=10
 * */
function getUserDatumInfo_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var type = checkUtil.numberFromReq(req, 'type')||10;

    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getUserDatumInfo_v6_0(userId, type, function(error, result){
        if(error) {
            console.log('users.js [getUserDatumInfo_v6_0] getUserDatumInfo_v6_0 Err:' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, result, res);
    });
}
router.get('/getUserDatumInfo_v6_0', getUserDatumInfo_v6_0);
router.post('/getUserDatumInfo_v6_0', getUserDatumInfo_v6_0);

/**
 * 1-22: 更新用户预填资料信息
 *
 * 参数:device  请求来源
 * 参数:userId  用户唯一标识
 * 参数:type    信息类型: 10用户资料(默认), 20公司资料
 * 参数:datum   用户填写信息的数组 json 字符串
 *              与 1-21 /v5/users/getUserDatumInfo_v6_0 接口返回的 datum 结构一致
 * 参数:ver     提纲结构版本号
 * 参数:updCnt  版本号内提纲模版修改次数
 * 参数:autoFill 是否自动填充, 0 不填充, 1 填充
 *
 * 返回值:
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {}
 * }
 *
 * */
function updateUserDatumInfo_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var type = checkUtil.numberFromReq(req, 'type')||10;
    var ver = checkUtil.numberFromReq(req, 'ver')||0;
    var updCnt = checkUtil.numberFromReq(req, 'updCnt')||0;
    var datum = checkUtil.stringFromReq(req, 'datum')||'';
    var autoFill = checkUtil.numberFromReq(req, 'autoFill')||0;
    var dtId = checkUtil.numberFromReq(req, 'dtId') || 0;

    if(userId <=0 || ver <=0 || updCnt <=0 || dtId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.updUserDatumInfo_v6_0(userId, type, datum, ver, updCnt, autoFill, dtId,function(error, result){
        if(error) {
            console.log('users.js [updUserDatumInfo_v6_0] updUserDatumInfo_v6_0 Err:' + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, result, res);
    });
}
router.get('/updateUserDatumInfo_v6_0', updateUserDatumInfo_v6_0);
router.post('/updateUserDatumInfo_v6_0', updateUserDatumInfo_v6_0);
//-----------------------------------------------------------------------------------------------
/*
 * 设置用户预填信息是否自动填充
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识, 与手机号至少要传递一个, 若均传递, 以 userId 为准
 * 参数: autoFill	是否自动填充, 0 不填充, 1 填充
 *  返回结果	{“msg”:”成功","data":{},"success":1}
 * */

function setUserDatumAutoFill_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var autoFill = checkUtil.numberFromReq(req, 'autoFill')||0;


    usersUtil.setUserDatumAutoFill_v6_0(userId, autoFill, function(error, result){
        if(error) {
           console.log("v5/users.js [setUserDatumAutoFill_v6_0] setUserDatumAutoFill_v6_0 err: " + error);
           return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
    });

}
router.get('/setUserDatumAutoFill_v6_0', setUserDatumAutoFill_v6_0);
router.post('/setUserDatumAutoFill_v6_0', setUserDatumAutoFill_v6_0);

//------------------------------------------------------------------------------------------------
/**
 * 1-18: 用户获取开通 vip 支付参数 Android版
 *
 * 参数:device	0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3 标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网
 * 参数: userId	用户唯一标识
 * 参数: itemId	虚拟商品id
 * 参数: couponId	优惠券id, 若没有传递 -1
 *
 * 返回值:
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *    "orderId" : 981,
 *    "orderNo" : "ASDFGHJKL",
 *    "prepayId": 789,
 *    "nonceStr": "qwertyuiopsdfghjkl",
 *    "timeStamp": 999990909090,
 *    "sign": "QWKSJDFHGJHDFHHDHH"
 *  }
 * }
 *
 * 测试地址: http://localhost:3000/v5/users/createVipOrderAndPayWX_v6_0?device=4&userId=299174&itemId=638
 * */
function createVipOrderAndPayWX_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var itemId = checkUtil.numberFromReq(req, 'itemId')||0;
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    couponId = couponId <= 0 ? 0 : couponId;

    if(userId <= 0 || device<0 || itemId<=0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    // 创建订单
    printUtil.createVipMemberOrder_v6_0(device, userId, itemId, couponId, function(crtErr, crtOrderInfo){
        if(crtErr) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        // web
        if(device == 4) {
            payUtil.getUnifiedOrderWeb(device, userId, crtOrderInfo.orderId, 40, function(getErr, getRet){
                if(getErr || !getRet){
                    return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }
                var data = {
                    orderId: crtOrderInfo.orderId,
                    orderNo: crtOrderInfo.orderNo,
                    codeUrl : getRet.code_url || '',
                    prepayId : getRet.prepay_id || '',
                    nonceStr: '',
                    timeStamp: '',
                    sign: ''
                };
                return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
            });
            return;
        }
        // app 调用微信支付
        payUtil.getUnifiedOrder(device, userId, null, crtOrderInfo.orderId, 40, function(getErr, getRet){
            if(getErr){
                return usersUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }

            var data = {
                orderId: crtOrderInfo.orderId,
                orderNo: crtOrderInfo.orderNo,
                prepayId: '',
                nonceStr: '',
                timeStamp: '',
                sign: '',
                codeUrl : ''
            };
            if(getRet) {
                data.prepayId = getRet.prepayId||'';
                data.nonceStr = getRet.nonceStr||'';
                data.timeStamp = getRet.timeStamp||'';
                data.sign = getRet.sign||'';
            }
            return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
        });
    });
}
router.get('/createVipOrderAndPayWX_v6_0', createVipOrderAndPayWX_v6_0);
router.post('/createVipOrderAndPayWX_v6_0', createVipOrderAndPayWX_v6_0);

//------------------------------------------------------------------------------------------------
/**
 * 用户获取开通 vip 支付参数 iOS版
 *
 * 参数:device	0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3 标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网
 * 参数: userId	用户唯一标识
 * 参数: itemId	虚拟商品id
 * 参数: couponId	优惠券id, 若没有传递 -1
 *
 * 返回值:
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *    "orderId" : 981,
 *    "orderNo" : "ASDFGHJKL",
 *    "IAPProductIdentifier" : "00000001A"
 *  }
 * }
 *
 * */
function createVipOrderAndPayIAP_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var itemId = checkUtil.numberFromReq(req, 'itemId')||0;
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    couponId = couponId <= 0 ? 0 : couponId;

    if(userId <= 0 || device<0 || itemId<=0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    // 创建订单
    printUtil.createVipMemberOrder_v6_0(device, userId, itemId, couponId, function(crtErr, crtOrderInfo){
        if(crtErr) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        // 0000000001 vip 原价
        // 0000000002 vip 优惠100
        var data = {
            orderId: crtOrderInfo.orderId,
            orderNo: crtOrderInfo.orderNo,
            IAPProductIdentifier: '0000000001',// TODO
        };
        if(crtOrderInfo.useCoupon) {
            data.IAPProductIdentifier = '0000000002';// TODO
        }

        if(itemId === 672 && !crtOrderInfo.useCoupon) { // 年度不使用优惠券
            data.IAPProductIdentifier = '0000000001';// TODO
        }
        if(itemId === 672 && crtOrderInfo.useCoupon) { // 年度使用优惠券
            data.IAPProductIdentifier = '0000000002';// TODO
        }

        if(itemId === 1700) { // 季度会员, 不可使用优惠券
            data.IAPProductIdentifier = '0000000003';// TODO
        }
        if(itemId === 1701) { // 月度会员, 不可使用优惠券
            data.IAPProductIdentifier = '0000000004';// TODO
        }

        if(itemId === 3242) {  // 季度特价
            data.IAPProductIdentifier = 'yjsc_season_minus_20';// TODO
        }
        if(itemId === 3243) {  // 约定特价
            data.IAPProductIdentifier = 'yjsc_month_minus_15';// TODO
        }


        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
    });
}
router.get('/createVipOrderAndPayIAP_v6_0', createVipOrderAndPayIAP_v6_0);
router.post('/createVipOrderAndPayIAP_v6_0', createVipOrderAndPayIAP_v6_0);


//----------------------------------------------------------------------------------------------
/**
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识, 与手机号至少要传递一个, 若均传递, 以 userId 为准
 * 参数: mobile	用户手机号, 与 userId 至少要传递一个, 若均传递, 以 userId 为准
 * 返回结果:	"{
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "userId": 1055,
 *   "userType": 1,
 *   "mobile": 13297922921,
 *   "registerUUID": "QWERTYUIOP-iOS",
 *   "nickName": "哈哈",
 *   "headUrl": "http://www.itbour.com/header/xxx.png",
 *   "userSign": "我就是不写签名咋地了",
 *   "accessory": [
 *    {
 *       "platform": 1,
 *       "nickName": "平台一昵称",
 *       "headerUrl": "平台一头像",
 *       "field1": "平台一字段一",
 *       "filed2": "平台一字段二",
 *        "field3": "平台一字段三",
 *       "field4": "平台一字段四",
 *        "field5": "平台一字段五"
 *      }
 *    ],
 *    "vipInfo" : {"vip" : 10,"expiry_time" : "2017-12-8 14:28”}, // 非 vip 字段为空
 *    "partnerInfo" : {"partner_id" : 985,"level" : 10}, // 非合伙人, 字段为空
 *    "hxInfo" : {"hx_id" : 211,"hx_psw" : “xcset”},  // 没有则创建
 *  }
 * }"
 * 注意:	"若用户不存在, 直接返回失败即可
 * http://localhost:3000/v5/users/getUsersDetailInfo_v6_0?device=1&userId=299188&mobile=18256276313
 * */
function getUsersDetailInfo_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var mobile = checkUtil.numberFromReq(req, 'mobile')||0;

    if(mobile <= 0 && userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getUsersDetailInfo_v6_0(userId, mobile, function(error, data){
        if(error) {
            console.log("/v5/users [getUsersDetailInfo_v6_0] getUsersDetailInfo_v6_0 err: " + error);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
    });
}
router.get('/getUsersDetailInfo_v6_0', getUsersDetailInfo_v6_0);
router.post('/getUsersDetailInfo_v6_0', getUsersDetailInfo_v6_0);


//--------------------------------  iOS 更新用户订单状态 ----------------------------
/**
     * 参数: device	"0表示从p0 表示从pc来的请求
     1 标识一键生成iOS端
     2 标识一键生成android端
     3  标识一键生成 app 嵌入网页
     4 标识一键生成 web 端
     5 标识一键生成微信端

     101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
     201 标识利楚商务
     301 标识酒单网"
     参数: userId	用户唯一标识, 与手机号至少要传递一个, 若均传递, 以 userId 为准
     参数[可选]: transactionId	当前交易号, 交易成功才有
     参数: receiptData	交易验证凭据, base64 编码, 注意+号问题
     参数: orderId	获取参数时的订单唯一标识
     参数: state	"移动端监听到的交易状态 11支付成功、12支付失败"
     返回结果	"{
      "success": 1,
      "msg": "成功",
      "data": {
        "state" : 12 // 若传递 transaction_id, 则为该交易的状态, 与后台订单状态保持一致
      }
    }"
 *
 * */
function updateVipOrderState_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var transactionId = checkUtil.numberFromReq(req, 'transactionId') || 0;
    var receiptData = checkUtil.stringFromReq(req, 'receiptData');
    var orderId = checkUtil.numberFromReq(req, 'orderId') || 0;
    var state = checkUtil.numberFromReq(req, 'state') || 0; //11支付成功、12支付失败
    // 异常状态标识, 0 标识无异常, 1 标识有异常, 但前端通过缓存已解决, 2, 标识有异常, 前端通过缓存仍无法结局
    var exceptionType = checkUtil.numberFromReq(req, 'exceptionType') || 0;


    // 注意: 从未购买过的用户, recipeData 为空, 所以只检查用户 id 订单 id, 订单状态
    if(userId <=0 || orderId <= 0 || state <=0 ) {
        usersUtil.handleIAPExceptionWithUserId(userId, orderId, state, transactionId, receiptData, exceptionType, function(cacheErr){
            if(cacheErr) {
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            console.log('/v5/users.js [updateVipOrderState_v6_0] handleIAPExceptionWithUserId success');
            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);
        });
    }
    // 正常状态处理
    else {
        usersUtil.updateVipOrderState_v6_0(userId, orderId, state, transactionId, receiptData,exceptionType, function(error, realState){

            if(error) {
                console.log('/v5/users.js [updateVipOrderState_v6_0] updateVipOrderState_v6_0 err: ' + error);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{state:realState},res);
        });
    }
}
router.get('/updateVipOrderState_v6_0', updateVipOrderState_v6_0);
router.post('/updateVipOrderState_v6_0', updateVipOrderState_v6_0);

/**
 * 用户分享后领取优惠券
 * 参数: device	"0表示从p0 表示从pc来的请求
 1 标识一键生成iOS端
 2 标识一键生成android端
 3  标识一键生成 app 嵌入网页
 4 标识一键生成 web 端
 5 标识一键生成微信端

 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 201 标识利楚商务
 301 标识酒单网"
 参数: userId	 用户唯一标识
 * 测试地址: http://localhost:3000/v5/users/getShareAwardCoupon_v6_0?device=1&userId=299188
 * */
function getShareAwardCoupon_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;

    if(userId <= 0) {
        return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
    }

    usersUtil.getShareAwardCoupon_v6_0(userId, function(error, coupons){
       if(error) {

           if(typeof error == 'string') {
               return usersUtil.ret_func_json(0, error, {}, res);
           }
           return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
       }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{coupons:coupons},res);
    });
}
router.get('/getShareAwardCoupon_v6_0', getShareAwardCoupon_v6_0);
router.post('/getShareAwardCoupon_v6_0', getShareAwardCoupon_v6_0);


/**
 * 城市合伙人查看实时排行
 * 城市合伙人查看在当前月内的、自己注册地址所在区内的所有城市合伙人的销售额（城市合伙人的绑定用户的除去邮费的订单的总额）排行
 * @param device
 * @param userId
 * @param pageNum
 * @param pageSize
 * @return
 * {
 *    "success":1,
 *    "msg":"成功",
 *    "data":{
 *        "area":"武汉市洪山区",
 *        "period":"20170601至20170624",
 *        "list":[
 *            {
 *                "rank":989,
 *                "mobile":"188****2619",
 *                "orderSum":100,
 *                "incomeSum":3
 *            }
 *        ],
 *        "pageNum":3,
 *        "totalPage":5
 *    }
 * }
 */
function getCityPartnerLatestRankList_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    //参数判断
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getCityPartnerLatestRankList_v6_1(userId, pageNum, pageSize, function(err, ret){
        if(err) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
    });
}
router.get('/getCityPartnerLatestRankList_v6_1', getCityPartnerLatestRankList_v6_1);
router.post('/getCityPartnerLatestRankList_v6_1', getCityPartnerLatestRankList_v6_1);

/**
 * 城市合伙人查看月度销售冠军历史
 * 城市合伙人查看每个月、自己注册地址所在区内的所有城市合伙人的销售额（城市合伙人的绑定用户的除去邮费的订单的总额）的销售冠军的历史
 * @param device
 * @param userId
 * @param pageNum
 * @param pageSize
 * @return
 * {
 *    "success":1,
 *    "msg":"成功",
 *    "data":{
 *        "area":"武汉市洪山区",
 *        "list":[
 *            {
 *                "year":2017,
 *                "month":"7",
 *                "mobile":"188****2619",
 *                "orderSum":100,
 *                "incomeSum":3
 *            }
 *        ],
 *        "pageNum":3,
 *        "totalPage":5
 *    }
 * }
 */
function getCityPartnerRankHistory_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    //参数判断
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    usersUtil.getCityPartnerRankHistory_v6_1(userId, pageNum, pageSize, function(err, ret){
        if(err) {
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,ret,res);
    });
}
router.get('/getCityPartnerRankHistory_v6_1', getCityPartnerRankHistory_v6_1);
router.post('/getCityPartnerRankHistory_v6_1', getCityPartnerRankHistory_v6_1);

//------------------------------------------------------------------------------------------
/**
 * 获取城市合伙人邀请合伙人的分享信息
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 返回结果:	"{
 *	"success" : 1,
 *	"msg" : "成功",
 *	"data" : {
 *		"url" : "http://www.itbour.com/activity/coupon.html?partnerId=9098723467",
 *		"title" : "加入合伙人",
 *		"content" : “您的好友邀请您加入一键生成合伙人计划",
 *		"imageUrl" " "http://oss-itbour.com"
 *	}
 *}"
 *
 * 测试地址: http://localhost:3000/v5/users/getInviteCityPartenerInfo_v6_1?userId=299174&device=1
 * */
function getInviteCityPartenerInfo_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    //参数判断
    if(userId <= 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    // 检查合伙人
    usersUtil.isValidCityPartner(userId, function(chkErr, isValid) {
        if (chkErr) {
            console.log('users.js [getInviteCityPartenerInfo_v6_1] isValidCityPartner err:' + chkErr);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        if(isValid) {
            var uId = parseInt(userId+187020).toString(20);// 变换userId
            var param = EncryptUtil.genSimpleEncryptInfo(uId);

            var url = 'http://www.itbour.com/cityPartner/v6_1_login.html';
            if(CONFIG.DEBUG){
                url = 'http://www.itbour.com/cityPartner/v6_1_login.html';
            }
            url += '?q='+param.q+'&t='+param.t+'&c='+param.c;

            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {
                url: url,
                title: '一键生成城市合伙人限量招募',
                content: '您的朋友邀请您成为"一键生成"的城市合伙人,速来申请,轻松赚取提成',
                imageUrl: 'http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U13/2017/05/17/205541498_HaRJtrbSV9l1D7nvG9qw'
            }, res);

        } else {
            return usersUtil.ret_func_json(0, '无效用户', {}, res);
        }
    });
}
router.get('/getInviteCityPartenerInfo_v6_1', getInviteCityPartenerInfo_v6_1);
router.post('/getInviteCityPartenerInfo_v6_1', getInviteCityPartenerInfo_v6_1);

//------------------------------------------------------------------------------------------
/**
 * 获取手机号对应的用户信息,若不存在该用户则根据手机号创建
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端

 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: mobile	 手机号
 * 返回结果:	"{
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *    "userId": 1055,
 *    "userType": 1,
 *    "mobile": 13297922921,
 *    "registerUUID": "QWERTYUIOP-iOS",
 *    "nickName": "哈哈",
 *    "headUrl": "http://www.itbour.com/header/xxx.png",
 *    "userSign": "我就是不写签名咋地了",
 *    "accessory": [
 *      {
 *        "platform": 1,
 *        "nickName": "平台一昵称",
 *        "headerUrl": "平台一头像",
 *        "field1": "平台一字段一",
 *        "filed2": "平台一字段二",
 *        "field3": "平台一字段三",
 *        "field4": "平台一字段四",
 *        "field5": "平台一字段五"
 *     }
 *    ],
 *     "vipInfo" : {"vip" : 10,"expiry_time" : "2017-12-8 14:28”}, // 非 vip 字段为空
 *    "partnerInfo" : {"partner_id" : 985,"level" : 10}, // 非合伙人, 字段为空
 *     "hxInfo" : {"hx_id" : 211,"hx_psw" : “xcset”},  // 没有则创建
 *  }
 * }"
 *
 * 测试地址: http://localhost:3000/v5/users/getNoneNullMobileUserInfo_v6_1?device=1&mobile=18256276313&uuid=QWERTYUIO
 * */
function getNoneNullMobileUserInfo_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var mobile = checkUtil.numberFromReq(req, 'mobile')||0;
    var uuid = checkUtil.stringFromReq(req, 'uuid') || '';
    //参数判断
    if(mobile <= 0 || mobile.toString().length != 11) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    if(!uuid || uuid.length == 0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }
    // 1. 查询用户, 若不存在则创建
    usersUtil.findInsertUser(mobile, uuid, function(findInsertUserErr, userItem){
        if(findInsertUserErr || !userItem) {
            console.log('v5/users.js [findInsertUser] findInsertUser err: ' + findInsertUserErr);
            return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }
        // 2. 获取用户详细信息
        usersUtil.getUsersDetailInfo_v6_0(userItem.user_id, mobile, function(getDetailErr, userInfo){
            if(getDetailErr) {
                console.log('v5/users.js [getUsersDetailInfo_v6_0] getUsersDetailInfo_v6_0 err: ' + getDetailErr);
                return usersUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
            }
            return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,userInfo,res);
        });
    });
}
router.get('/getNoneNullMobileUserInfo_v6_1', getNoneNullMobileUserInfo_v6_1);
router.post('/getNoneNullMobileUserInfo_v6_1', getNoneNullMobileUserInfo_v6_1);

/**
 * 小程序, 微信登录, 若用户存在, 返回用户信息, 否则注册后返回用户信息
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 6 标识小程序
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: nickName	微信昵称
 * 参数: unionId	微信用户唯一标识
 *
 * 测试地址: http://localhost:3000/v5/users/wxLogin_v6_2?device=6&unionId=o07tHv8t_vQhJ_3o3YLaKrNKK-os&nickName=哈哈&uuid=sEkjuxnUK0tB8dyiGvoLyt5vN22we-5p::ffff:192.168.31.2529o7Zs-pc
 * */

function miniProgramLogin_v6_2(req, res, next) {

    var device = checkUtil.numberFromReq(req, 'device');
    var nickName = checkUtil.stringFromReq(req, 'nickName');
    var unionId = checkUtil.stringFromReq(req, 'unionId');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!unionId || unionId.length <=0 ) {
        return usersUtil.ret_func_json(0, 'unionId 无效', {}, res);
    }
    var userInfo = {
        'nickName' : nickName || '',
        'uuid' : uuid || ''
    };

    usersUtil.getUserIdByWechatInfoForMiniProgram(unionId,userInfo, function(getUserIdErr, userId){
        if(getUserIdErr) {
            var errMsg = typeof getUserIdErr == 'string' ? getUserIdErr : CODE.OPERATION_FAILED;
            console.log('v5/users.js [miniProgramLogin_v6_2] getUserIdErr: ' + getUserIdErr);
            return usersUtil.ret_func_json(0, errMsg, {}, res);
        }

        usersUtil.getUsersDetailInfo_v6_0(userId, null, function(getUserInfoErr, userInfo){
            if(getUserInfoErr) {
                var errMsg = typeof getUserInfoErr == 'string' ? getUserInfoErr : CODE.OPERATION_FAILED;
                console.log('v5/users.js [miniProgramLogin_v6_2] getUserInfoErr: ' + getUserInfoErr);
                return usersUtil.ret_func_json(0, errMsg, {}, res);
            }

            return usersUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, userInfo, res);
        });
    });
}
router.get('/wxLogin_v6_2', miniProgramLogin_v6_2);
router.post('/wxLogin_v6_2', miniProgramLogin_v6_2);



//===============================================================================================
module.exports = router;